<?php

namespace Biz\model;


use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;

class ShopComments extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'shop_comments';

    const _SUB_TABLE = false;


    protected static $fields = [
        'shop_id',
        'order_no',
        'uid',
        'grade',
        'content' => ['trim', 'strip_tags'],
    ];


    public static function addComment($order_no, $shop_id, $uid, $grade, $content)
    {

        $data = self::buidData([
            'shop_id' => $shop_id,
            'order_no' => $order_no,
            'uid' => $uid,
            'grade' => $grade,
            'content' => $content,
        ]);

        $data['add_time'] = date("Y-m-d H:i:s");

        self::insert($data);

        return self::id();
    }

    public static function getAvgScore($shop_id)
    {
//        $avgScore = self::get(['grade' => Medoo::raw("AVG(<grade>)")], ['shop_id' => $shop_id])['grade'];

//        $score = "1.0";

        return "5.0"; //默认 4.5
//        if ($avgScore > 1) {
//            $v = ($avgScore / 0.5);
//
//            if (strpos($v, ".") === false) {
//
//                 $score = sprintf("%.1F", ((int)($avgScore)));
//
//            } else {
//
//                 $score = sprintf("%.1F", ((int)($avgScore / 0.5) + 1) * 0.5);
//            }
//
//        }
//
//        return $score;
    }

    public static function admSearch($params, $page, $pagesize)
	{
		$where = [
			'ORDER' => ['add_time' => 'DESC']
		];
		if (isset($params['grade']) && $params['grade']) {
			$where['AND']['grade'] = $params['grade'];
		}
		if (isset($params['shop_id']) && $params['shop_id']) {
			$where['AND']['shop_id'] = $params['shop_id'];
		}
		if (isset($params['grade']) && $params['grade']) {
			$where['AND']['grade'] = $params['grade'];
		}
		if (isset($params['uid']) && $params['uid']) {
			$where['AND']['uid'] = $params['uid'];
		}
		if (isset($params['order_no']) && $params['order_no']) {
			$where['AND']['order_no'] = $params['order_no'];
		}
		if (isset($params['start_time']) && $params['start_time'] && isset($params['end_time']) && $params['end_time']) {
			$where['AND']['add_time[>]'] = $params['start_time'];
			$where['AND']['add_time[<]'] = date('Y-m-d',strtotime($params['end_time']) + 86400);
		}

		return [
			'count' => self::count($where),
			'list' => self::select('*', array_merge($where, [
				'LIMIT' => [($page - 1) * $pagesize, $pagesize]
			]))
		];

	}

}